#!/usr/bin/python
import os, glob, time, urllib2, urllib, re, cookielib
from encode import multipart_encode
import streaminghttp
from CivPbemConfig import CivPbemConfig
import sys


#*********************** Set up Logging *********************************
try:
    f = open ('output.txt', 'w')
    f.write ('Civ PBEM Uploader script log output:\n')
    log_enabled = True
except:
    print "Output file not opened successfully. Logging is not available"
    log_enabled = False


#*********************** Import Config Settings *************************

if (log_enabled == True):
    config_container = CivPbemConfig("config.xml", f)
else:
    config_container = CivPbemConfig("config.xml")
if (config_container.version != 1):
    raise ConfigError ("File version does not match! Expecting file version 1")
username = config_container.user
password = config_container.password
url = config_container.url
root = config_container.file_path
gameName = config_container.game_name
message_to_next_user = config_container.message_to_next_user
log_level = config_container.log_level

if (log_level > 0):
    log_enabled = True
else:
    if (log_enabled == True):
        f.close()
    log_enabled = False

#***************************** FIND FILE *********************************

#Grab the latest file
 
 
date_file_list = []
for folder in glob.glob(root):
    # select the type of file, for instance *.jpg or all files *.*
    # theoretically, we could change this to *.CivBeyondTheSwordSave to make the search more specific, 
    # but this directory should only hold game saves, right? 
    for file in glob.glob(folder + '/*.*'):
    # retrieves the stats for the current file as a tuple
    # (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
    # the tuple element mtime at index 8 is the last-modified-date
    # no, I didn't write some of these detailed comments.
        stats = os.stat(file)
    # create tuple (year yyyy, month(1-12), day(1-31), hour(0-23), minute(0-59), second(0-59),
    # weekday(0-6, 0 is monday), Julian day(1-366), daylight flag(-1,0 or 1)) from seconds since epoch
    # note: this tuple can be sorted properly by date and time
        lastmod_date = time.localtime(stats[8])
    # create list of tuples ready for sorting by date
        date_file_tuple = lastmod_date, file
        date_file_list.append(date_file_tuple)
 
 
date_file_list.sort()
date_file_list.reverse() # newest mod date now first
#This (latest_file) is the important bit of data. The rest of the file list is now unnecessary
latest_file = date_file_list[0]
latest_file_folder, latest_file_name = os.path.split(latest_file[1])
if (log_enabled == True):
    f.write ('\nlatest_file_folder = ' + latest_file_folder)
    f.write ('\nlatest_file = ' + latest_file_name)
else:
    print '\nlatest_file_folder = ' + latest_file_folder
    print '\nlatest_file = ' + latest_file_name

#************************* LOGIN *************************************

#Install cookie support to the urllib2 opener
cookies = cookielib.CookieJar()
opener = streaminghttp.register_openers()
opener.add_handler(urllib2.HTTPCookieProcessor(cookies))

#Format the POST data to capture the cookie
data = urllib.urlencode({'username' : username, 'password' : password})

#Send the POST request
req = urllib2.Request('http://www.pbemtracker.com/login.php', data)
urllib2.urlopen(req)


#****************************** UPLOAD *********************************
#This url too may need to change for a different game. We should eventually create a configuration 
#section at the top of the file where all this info will be held, along with a variable for gameID
#that automatically corrects the URLs depending on which game ID we're using. We'll make that a @TODO
#upload_url = "http://www.pbemtracker.com/submitturn.php?gameID=95"
#This could be derived from the filename, and in fact is in the perl script used for the web page. 
#It's easier, however, just to hard code it for now. We may need to update this in the future
#if we are using this script for multiple games, although other things (like game id) would need to be
#changed as well.


#unfortunately, timeFrame has to be derived. Time for regular expressions!
reg = "(AD|BC)-[0-9]+"
reg_output = re.search(reg, latest_file_name)

if (reg_output is None):
    if (log_enabled == True):
        f.write ("\nMalformed file name, no date found") 
    else:
        print "Malformed file name, no date found"
else:
    year = reg_output.group(0)

split_year = year.partition('-')

era = split_year[0]
year_number = split_year[2]

timeFrame = year_number + " " + era


#Who you send the save to, derived from the filename...
reg = "_to_[^\.]+"
reg_output = re.search(reg, latest_file_name)

if (reg_output is None):
    if (log_enabled == True):
        f.write ("\nMalformed file name, no user found")
    else:
        print "Malformed file name, no user found"
else:
    next_user = reg_output.group(0)[4:]




upload_params = {"to" : next_user, "from": "Civ PBEM Tracker ", "subject" : gameName + " - " + timeFrame, "message" : message_to_next_user, "fileName" : latest_file_name, "timeFrame" : timeFrame, "gameName" : gameName ,"uploaded" : open(latest_file_folder + '\\' + latest_file_name, 'rb')}

datagen, headers = multipart_encode(upload_params)

resp = urllib2.Request(url, datagen, headers)
resp.add_header('Referer', url)
resp.add_header('Connection', 'keep-alive')
resp.add_header('Keep-Alive', '115')
resp.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 5.1; rv:2.0b7) Gecko/20100101 Firefox/4.0b7')
cookie_val = next(iter(cookies)).value
resp.add_header('Cookie', 'pbemLoggedInUserID='+cookie_val)

resp = urllib2.urlopen(resp).read()

if (log_enabled == True):
    try:
        re.search("Your message has been successfully sent",resp).group(0)
        f.write('\nSuccess!!\n' + latest_file_name + '\nSent to ' + next_user)
    except:
        f.write('\nSend failed, try again')

    if (log_level == 2):
        f.write ("\nCookie value is: \n" + cookie_val)

    f.write ("\nResponse is: \n")
    f.write (resp)
    f.close()
    
else:
    try:
        re.search("Your message has been successfully sent",resp).group(0)
        print 'Success!!\n' + latest_file_name + '\nSent to ' + next_user
    except:
        print 'Send failed, try again'



